package search

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"grpc/basic/global"
	__ "grpc/basic/proto"
	"grpc/handle/model"
	"grpc/pkg"
	"strconv"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	//pb.UnimplementedGreeterServer
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SayHello(_ context.Context, in *__.StreamReq) (*__.StreamResp, error) {

	return &__.StreamResp{}, nil
}

func (s *Server) AddVideo(_ context.Context, in *__.AddVideoReq) (*__.AddVideoResp, error) {

	var user model.User
	if err := user.VeryUser(global.DB, int(in.UserId)); err != nil {
		return nil, fmt.Errorf("用户不存在")
	}

	var video model.Video

	video = model.Video{
		UserId:  int(in.UserId),
		Title:   in.Title,
		Intrude: in.Intrude,
		Image:   in.Image,
		Status:  in.Status,
	}

	if err := video.AddVideo(global.DB); err != nil {
		return nil, fmt.Errorf("视频上传失败")
	}

	handler, err := pkg.TokenHandler(strconv.Itoa(video.UserId))
	if err != nil {
		return nil, err
	}

	return &__.AddVideoResp{
		Greet:   "视频上传成功",
		VideoId: int64(video.ID),
		Token:   handler,
	}, nil
}

func (s *Server) ListVideo(_ context.Context, in *__.ListVideoReq) (*__.ListVideoResp, error) {

	var video model.Video

	if err := video.ListVideo(global.DB, int(in.Id)); err != nil {
		return nil, fmt.Errorf("查询失败")
	}

	return &__.ListVideoResp{
		Greet:   "查询成功",
		UserId:  int64(video.UserId),
		Title:   video.Title,
		Intrude: video.Intrude,
		Image:   video.Image,
		Status:  video.Status,
	}, nil
}

func (s *Server) AddOrder(_ context.Context, in *__.AddOrderReq) (*__.AddOrderResp, error) {

	var user model.User
	if err := user.VeryUser(global.DB, int(in.UserId)); err != nil {
		return nil, fmt.Errorf("用户不存在")
	}

	var video model.Member

	if err := video.VeryMem(global.DB, int(in.MemberId)); err != nil {
		return nil, fmt.Errorf("会员不存在")
	}

	var order model.Order

	order = model.Order{
		UserId:   int(in.UserId),
		MemberId: int(in.MemberId),
		OrderSn:  uuid.NewString(),
		Price:    video.Price,
		Method:   in.Method,
		Status:   in.Status,
	}

	if err := order.AddOrder(global.DB); err != nil {
		return nil, fmt.Errorf("支付创建失败")
	}

	url := strconv.Itoa(int(order.Price))
	pay, err := pkg.AliPay(order.OrderSn, url)
	if err != nil {
		return nil, err
	}
	return &__.AddOrderResp{
		Greet: "支付订单创建成功",
		Url:   pay,
	}, nil
}
